package com.lx.design.demo.java.base.map.merge;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lx
 * @date 2021/3/5 11:51
 */
public class Merge {

    public static void main(String[] args) throws JsonProcessingException {
        //普通操作
        generalOption();

        //merge
        Merge merge = new Merge();
        merge.merge();

        merge2();
    }

    /**
     *
     * merge() 可以这么理解：它将新的值赋值到 key （如果不存在）或更新给定的key 值对应的 value，其源码如下：
     *
     *     default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
     *         Objects.requireNonNull(remappingFunction);
     *         Objects.requireNonNull(value);
     *         V oldValue = this.get(key);
     *         V newValue = oldValue == null ? value : remappingFunction.apply(oldValue, value);
     *         if (newValue == null) {
     *             this.remove(key);
     *         } else {
     *             this.put(key, newValue);
     *         }
     *
     *         return newValue;
     *     }
     *
     * 我们可以看到原理也是很简单的，该方法接收三个参数，一个 key 值，一个 value，一个 remappingFunction ，如果给定的key不存在，它就变成了 put(key, value) 。
     *
     * 但是，如果 key 已经存在一些值，我们 remappingFunction 可以选择合并的方式，然后将合并得到的 newValue 赋值给原先的 key。
     * @throws JsonProcessingException e
     */
    private void merge() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        List<StudentScore> studentScoreList = buildTestList();

        Map<String, Integer> studentScoreMap2 = new HashMap<>();
        studentScoreList.forEach(studentScore -> studentScoreMap2.merge(
                studentScore.getStuName(),
                studentScore.getScore(),
                this::handle));

        System.out.println(objectMapper.writeValueAsString(studentScoreMap2));
    }
    private static void merge2() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        List<StudentScore> studentScoreList = buildTestList();

        Map<String, Integer> studentScoreMap2 = new HashMap<>();
        studentScoreList.forEach(studentScore -> studentScoreMap2.merge(
                studentScore.getStuName(),
                studentScore.getScore(),
                Integer::sum));

        System.out.println(objectMapper.writeValueAsString(studentScoreMap2));
    }

    private int handle(int oldVal, int newVal){
        return oldVal+newVal;
    }
    public static void generalOption() throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        List<StudentScore> studentScoreList = buildTestList();

        Map<String, Integer> studentScoreMap = new HashMap<>();
        studentScoreList.forEach(studentScore -> {
            if (studentScoreMap.containsKey(studentScore.getStuName())) {
                studentScoreMap.put(studentScore.getStuName(),
                        studentScoreMap.get(studentScore.getStuName()) + studentScore.getScore());
            } else {
                studentScoreMap.put(studentScore.getStuName(), studentScore.getScore());
            }
        });

        System.out.println(objectMapper.writeValueAsString(studentScoreMap));
    }

    private static List<StudentScore> buildTestList() {
        List<StudentScore> studentScoreList = new ArrayList<>();
        StudentScore studentScore1 = new StudentScore() {{
            setStuName("张三");
            setSubject("语文");
            setScore(70);
        }};
        StudentScore studentScore2 = new StudentScore() {{
            setStuName("张三");
            setSubject("数学");
            setScore(80);
        }};
        StudentScore studentScore3 = new StudentScore() {{
            setStuName("张三");
            setSubject("英语");
            setScore(65);
        }};
        StudentScore studentScore4 = new StudentScore() {{
            setStuName("李四");
            setSubject("语文");
            setScore(68);
        }};
        StudentScore studentScore5 = new StudentScore() {{
            setStuName("李四");
            setSubject("数学");
            setScore(70);
        }};
        StudentScore studentScore6 = new StudentScore() {{
            setStuName("李四");
            setSubject("英语");
            setScore(90);
        }};
        StudentScore studentScore7 = new StudentScore() {{
            setStuName("王五");
            setSubject("语文");
            setScore(80);
        }};
        StudentScore studentScore8 = new StudentScore() {{
            setStuName("王五");
            setSubject("数学");
            setScore(85);
        }};
        StudentScore studentScore9 = new StudentScore() {{
            setStuName("王五");
            setSubject("英语");
            setScore(70);
        }};

        studentScoreList.add(studentScore1);
        studentScoreList.add(studentScore2);
        studentScoreList.add(studentScore3);
        studentScoreList.add(studentScore4);
        studentScoreList.add(studentScore5);
        studentScoreList.add(studentScore6);
        studentScoreList.add(studentScore7);
        studentScoreList.add(studentScore8);
        studentScoreList.add(studentScore9);

        return studentScoreList;
    }
}
